package modules

import (
	"context"
	"encoding/json"

	"go-zero-admin/apps/modules/iot/cmd/link"
	"go-zero-admin/apps/modules/iot/cmd/link/network"
	"go-zero-admin/apps/modules/iot/cmd/link/network/constant"
	"go-zero-admin/apps/modules/iot/model"
	"go-zero-admin/pkg/tool"

	"github.com/Masterminds/squirrel"
	"github.com/zeromicro/go-zero/core/logx"
)

// NewLinkServer 创建link服务
func NewLinkServer(iotNetworkModel model.IotNetworkModel) {
	// 查询出所有标记为开启的网络组件
	listWhereBuilder := iotNetworkModel.RowBuilder()
	condition := squirrel.Eq{"state": constant.NetworkStateOpen}
	listWhereBuilder = listWhereBuilder.Where(condition)
	iotNetworkList, err := iotNetworkModel.FindAll(context.Background(), listWhereBuilder, "")
	if err != nil {
		logx.Errorf(tool.GetErrMsgHeaderFormat("IOT-RPC-LINK-ERR", "init link server"), err)
	}

	// 组装数据格式
	var networkConfigList []*network.NetworkProperties
	if len(iotNetworkList) != 0 {
		for _, v := range iotNetworkList {
			var config map[string]any
			err = json.Unmarshal([]byte(v.Configuration), &config)
			if err != nil {
				continue
			}
			networkConfigList = append(networkConfigList, &network.NetworkProperties{
				Id:             v.Id,
				Name:           v.Name,
				Enabled:        v.State == constant.NetworkStateOpen,
				Type:           v.Type,
				Configurations: config,
			})
		}
	}

	// 初始化link
	link.InitIot(networkConfigList)
}
